"""
RagFlow 客户端 GUI 配置选项卡组件
"""

import os
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QLabel, QLineEdit, QCheckBox, QPushButton, QMessageBox, QProgressDialog,
    QComboBox
)

from ragflow_client.config import RagFlowConfig
from ragflow_client.gui.components.threads import ConnectionTestThread


class ConfigTabWidget(QWidget):
    """配置选项卡组件"""
    
    # 定义信号
    config_saved = Signal(RagFlowConfig)
    
    def __init__(self, parent=None):
        """初始化配置选项卡组件"""
        super().__init__(parent)
        self.parent = parent
        self.current_thread = None
        self.setup_ui()
    
    def setup_ui(self):
        """创建界面"""
        # 创建布局
        layout = QGridLayout(self)
        # 设置更紧凑的布局
        layout.setVerticalSpacing(5)  # 进一步减少垂直间距
        layout.setContentsMargins(5, 5, 5, 5)  # 进一步减少边距
        
        # API URL
        layout.addWidget(QLabel("RagFlow API 地址:"), 0, 0)
        self.api_url_edit = QLineEdit()
        layout.addWidget(self.api_url_edit, 0, 1)
        
        # API Key
        layout.addWidget(QLabel("API 密钥:"), 1, 0)
        self.api_key_edit = QLineEdit()
        self.api_key_edit.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.api_key_edit, 1, 1)
        
        # 隐藏不需要的字段，但保留引用以避免错误
        self.kb_id_edit = QLineEdit()
        self.kb_name_edit = QLineEdit()
        self.parser_id_edit = QLineEdit()
        self.kb_id_edit.hide()
        self.kb_name_edit.hide()
        self.parser_id_edit.hide()
        
        # 模式设置布局
        mode_layout = QHBoxLayout()
        mode_layout.setSpacing(5)  # 减少水平间距
        mode_layout.setContentsMargins(0, 0, 0, 0)  # 移除边距
        layout.addLayout(mode_layout, 2, 0, 1, 2)
        
        # 调试模式
        self.debug_checkbox = QCheckBox("启用调试模式")
        self.debug_checkbox.toggled.connect(self.on_debug_toggled)
        mode_layout.addWidget(self.debug_checkbox)
        
        # 主题选择
        theme_layout = QHBoxLayout()
        theme_layout.setSpacing(5)  # 减少水平间距
        theme_layout.setContentsMargins(0, 0, 0, 0)  # 移除边距
        theme_layout.addWidget(QLabel("主题选择:"))
        self.theme_combo = QComboBox()
        # 设置下拉框最小宽度，确保文字能够完全显示
        self.theme_combo.setMinimumWidth(150)
        # 设置下拉框策略，使其能够显示完整文本
        self.theme_combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.theme_combo.addItem("浅色主题", "light")
        self.theme_combo.addItem("暗黑主题", "dark")
        # 未来可以添加更多主题
        # self.theme_combo.addItem("蓝色主题", "blue")
        # self.theme_combo.addItem("绿色主题", "green")
        self.theme_combo.currentIndexChanged.connect(self.on_theme_changed)
        theme_layout.addWidget(self.theme_combo)
        mode_layout.addLayout(theme_layout)
        
        # 兼容旧版本的暗黑模式复选框（隐藏）
        self.dark_mode_checkbox = QCheckBox("启用暗黑模式")
        self.dark_mode_checkbox.hide()
        
        # 添加弹性空间
        mode_layout.addStretch()
        
        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(5)  # 减少水平间距
        button_layout.setContentsMargins(0, 0, 0, 0)  # 移除边距
        layout.addLayout(button_layout, 3, 0, 1, 2)
        
        # 保存配置按钮
        save_button = QPushButton("保存配置")
        save_button.clicked.connect(self.save_config)
        button_layout.addWidget(save_button)
        
        # 测试连接按钮
        test_button = QPushButton("测试连接")
        test_button.clicked.connect(self.test_connection)
        button_layout.addWidget(test_button)
        
        # 添加弹性空间
        button_layout.addStretch()
    
    def on_debug_toggled(self, checked):
        """处理调试模式切换"""
        # 获取当前配置
        config = self.get_config()
        config.debug = checked
        
        # 发送信号
        self.config_saved.emit(config)
        
        # 保存到环境变量
        self.save_theme_and_debug(config.debug, config.theme)
    
    def on_theme_changed(self, index):
        """处理主题切换"""
        from ragflow_client.utils.logger import get_logger
        logger = get_logger(__name__)
        
        try:
            # 获取选择的主题
            theme = self.theme_combo.currentData()
            logger.debug(f"主题切换: {theme}")
            
            # 直接保存到环境变量
            self.save_theme_and_debug(self.debug_checkbox.isChecked(), theme)
            
            # 直接设置环境变量
            os.environ["THEME"] = theme
            
            # 创建新的配置对象
            config = RagFlowConfig(
                api_url=self.api_url_edit.text().strip(),
                api_key=self.api_key_edit.text().strip(),
                kb_id=self.kb_id_edit.text().strip(),
                kb_name=self.kb_name_edit.text().strip(),
                parser_id=self.parser_id_edit.text().strip(),
                doc_dir="",
                doc_suffix=[],
                debug=self.debug_checkbox.isChecked(),
                theme=theme  # 确保使用正确的主题
            )
            
            # 更新暗黑模式复选框状态（兼容旧版本）
            self.dark_mode_checkbox.setChecked(theme == "dark")
            
            # 发送信号
            self.config_saved.emit(config)
            
            # 立即应用主题
            if self.parent and hasattr(self.parent, 'apply_theme'):
                # 确保parent.config的theme值正确
                if hasattr(self.parent, 'config'):
                    self.parent.config.theme = theme
                
                # 应用主题
                self.parent.apply_theme()
                logger.debug(f"主题已应用，theme={theme}")
                
                # 强制刷新界面
                from PySide6.QtWidgets import QApplication
                QApplication.processEvents()
                
                # 显示主题已更改的消息
                theme_name = "暗黑主题" if theme == "dark" else "浅色主题"
                QMessageBox.information(self, "主题已更改", f"已切换到{theme_name}")
                
        except Exception as e:
            logger.error(f"切换主题失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"切换主题失败: {str(e)}")
            import traceback
            traceback.print_exc()
    
    def on_dark_mode_toggled(self, checked):
        """处理暗黑模式切换（兼容旧版本）"""
        # 更新主题下拉框
        index = 1 if checked else 0  # 1=dark, 0=light
        self.theme_combo.setCurrentIndex(index)
    
    def save_theme_and_debug(self, debug, theme):
        """保存主题和调试模式到环境变量"""
        from ragflow_client.utils.logger import get_logger
        from ragflow_client.utils.config_util import save_env_variable, load_env_file
        logger = get_logger(__name__)
        
        try:
            # 使用配置工具保存环境变量
            save_env_variable("DEBUG", 'true' if debug else 'false')
            save_env_variable("THEME", theme)
            save_env_variable("DARK_MODE", 'true' if theme == 'dark' else 'false')  # 兼容旧版本
            
            # 重新加载环境变量
            load_env_file()
            
            # 验证环境变量是否正确设置
            actual_theme = os.getenv("THEME", "")
            
            if actual_theme != theme:
                logger.error(f"环境变量设置失败: 期望THEME={theme}，实际THEME={actual_theme}")
                # 尝试直接设置环境变量
                os.environ["THEME"] = theme
            
            # 记录日志
            logger.debug(f"已保存配置: DEBUG={debug}, THEME={theme}")
            logger.debug(f"环境变量THEME={os.getenv('THEME')}")
            
        except Exception as e:
            logger.error(f"保存设置失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"保存设置失败: {str(e)}")
            import traceback
            traceback.print_exc()
    
    def fill_config_values(self, config: RagFlowConfig) -> None:
        """
        填充配置值到界面
        
        Args:
            config: 配置对象
        """
        self.api_url_edit.setText(config.api_url)
        self.api_key_edit.setText(config.api_key)
        self.kb_id_edit.setText(config.kb_id)
        self.kb_name_edit.setText(config.kb_name)
        self.parser_id_edit.setText(config.parser_id)
        self.debug_checkbox.setChecked(config.debug)
        
        # 设置主题下拉框
        theme_index = 0  # 默认为浅色主题
        if config.theme == "dark":
            theme_index = 1
        self.theme_combo.setCurrentIndex(theme_index)
        
        # 兼容旧版本
        self.dark_mode_checkbox.setChecked(config.dark_mode)
    
    def get_config(self) -> RagFlowConfig:
        """
        从界面获取配置
        
        Returns:
            配置对象
        """
        api_url = self.api_url_edit.text().strip()
        api_key = self.api_key_edit.text().strip()
        kb_id = self.kb_id_edit.text().strip()
        kb_name = self.kb_name_edit.text().strip()
        parser_id = self.parser_id_edit.text().strip()
        debug = self.debug_checkbox.isChecked()
        theme = self.theme_combo.currentData()
        
        return RagFlowConfig(
            api_url=api_url,
            api_key=api_key,
            kb_id=kb_id,
            kb_name=kb_name,
            parser_id=parser_id,
            doc_dir="",
            doc_suffix=[],
            debug=debug,
            theme=theme
        )
    
    def save_config(self) -> None:
        """保存配置"""
        from ragflow_client.utils.config_util import save_env_variable, load_env_file
        
        # 从界面获取配置
        config = self.get_config()
        
        # 验证必填字段
        if not config.api_url:
            QMessageBox.critical(self, "错误", "API 地址不能为空")
            return
        
        if not config.api_key:
            QMessageBox.critical(self, "错误", "API 密钥不能为空")
            return
        
        try:
            # 使用配置工具保存环境变量
            save_env_variable("DEBUG", 'true' if config.debug else 'false')
            save_env_variable("THEME", config.theme)
            save_env_variable("DARK_MODE", 'true' if config.theme == 'dark' else 'false')  # 兼容旧版本
            save_env_variable("RAGFLOW_API_URL", config.api_url)
            save_env_variable("RAGFLOW_API_KEY", config.api_key)
            
            # 添加其他配置项
            kb_id = config.kb_id if config.kb_id else ""
            kb_name = config.kb_name if config.kb_name else "处罚案例"
            parser_id = config.parser_id if config.parser_id else "naive"
            doc_dir = config.doc_dir if config.doc_dir else ""
            doc_suffix = ",".join(config.doc_suffix) if config.doc_suffix else "md,txt,pdf,docx"
            
            save_env_variable("RAGFLOW_KB_ID", kb_id)
            save_env_variable("RAGFLOW_KB_NAME", kb_name)
            save_env_variable("RAGFLOW_PARSER_ID", parser_id)
            save_env_variable("RAGFLOW_DOC_DIR", doc_dir)
            save_env_variable("RAGFLOW_DOC_SUFFIX", doc_suffix)
            
            # 重新加载环境变量
            load_env_file()
            
            QMessageBox.information(self, "成功", "配置已保存")
            
            # 发送信号
            self.config_saved.emit(config)
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}")
    
    def test_connection(self) -> None:
        """测试 API 连接"""
        # 从界面获取配置
        config = self.get_config()
        
        # 验证必填字段
        if not config.api_url:
            QMessageBox.critical(self, "错误", "API 地址不能为空")
            return
        
        if not config.api_key:
            QMessageBox.critical(self, "错误", "API 密钥不能为空")
            return
        
        # 创建进度对话框
        progress = QProgressDialog("正在测试连接...", "取消", 0, 0, self)
        progress.setWindowTitle("测试连接")
        progress.setWindowModality(Qt.WindowModal)
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.show()
        
        # 创建并启动工作线程
        self.current_thread = ConnectionTestThread(config)
        self.current_thread.finished.connect(lambda status, msg: self.handle_connection_result(status, msg, progress))
        progress.canceled.connect(self.current_thread.cancel)
        self.current_thread.start()
    
    def handle_connection_result(self, status: bool, msg: str, progress: QProgressDialog) -> None:
        """
        处理连接测试结果
        
        Args:
            status: 连接状态
            msg: 消息
            progress: 进度对话框
        """
        # 关闭进度对话框
        progress.close()
        
        # 显示结果
        if status:
            QMessageBox.information(self, "成功", f"连接成功: {msg}")
        else:
            QMessageBox.critical(self, "错误", f"连接失败: {msg}")
        
        # 清理线程
        self.current_thread = None